package com.example.filesystem.entity;

import cn.hutool.json.JSONObject;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author bbyh
 * @since 2025-04-27
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Slf4j
public class Result {
    private static final Integer SUCCESS = 200;
    private static final Integer ERROR = 500;

    private Object data;
    private Integer code;
    private String msg;

    public static Result success(Object data, String msg) {
        return new Result(data, SUCCESS, msg);
    }

    public static Result error(Object data, String msg) {
        return new Result(data, ERROR, msg);
    }

    public static void writeResult(HttpServletResponse response, String msg) {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.set("code", 500);
            jsonObject.set("msg", msg);
            response.setContentType("application/json,charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().print(jsonObject);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }
}
